package com.mingmen.canting.jingli;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.mingmen.canting.R;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.adapter.JingLiCaiLeftAdapter;
import com.mingmen.canting.adapter.JingLiCaiNewLeftAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.OnItemClickListener;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.JingliCaiGouDanModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class JingLiCaiGouNewListragment extends Fragment implements OnItemClickListener, JingLiCaiNewLeftAdapter.OnItemClickListener {


    @BindView(R.id.recyclerview_left)
    SwipeRecyclerView recyclerviewLeft;

    Unbinder unbinder;
    @BindView(R.id.btn_suofang)
    Button btnSuofang;
    @BindView(R.id.img_list)
    ImageView imgList;
    @BindView(R.id.ll_mycollection_bottom_dialog)
    LinearLayout llMycollectionBottomDialog;

    private String mTitle;


    LinearLayoutManager linearLayoutManager_left;

    public static JingLiCaiGouNewListragment getInstance(String title) {
        JingLiCaiGouNewListragment sf = new JingLiCaiGouNewListragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    LinearLayoutManager linearLayoutManager;
    JingLiCaiNewLeftAdapter jingLiLeftAdapter;
    List<String> leftArr = new ArrayList<>();
    String token;
    List<JingliCaiGouDanModel.DataBean> dataBeanList = new ArrayList<>();

    @BindView(R.id.btn_digndan)
    Button btn_digndan;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;

    TimePickerView pvTime;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;
    String startTime = "";
    String endTime = "";
    @BindView(R.id.layout_calenda_first)
    LinearLayout layout_calenda_first;
    @BindView(R.id.layout_calenda_second)
    LinearLayout layout_calenda_second;


    List<JingliCaiGouDanModel.DataBean> applyListBeanList = new ArrayList<>();

    int pageNumber = 1;

    @BindView(R.id.layout_data)
    LinearLayout layout_data;
    @BindView(R.id.recyclerview_right)
    SwipeRecyclerView recyclerview_right;
    JingLiRightAdapter jingLiExpandedAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frjingli_newdaishenhe, null);
        unbinder = ButterKnife.bind(this, v);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);

        linearLayoutManager = new LinearLayoutManager(getActivity());
//        recyclerview.setLayoutManager(linearLayoutManager);
        linearLayoutManager_left = new LinearLayoutManager(getActivity());
        recyclerviewLeft.setLayoutManager(linearLayoutManager_left);

        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        getCaneda();
        jingLiLeftAdapter = new JingLiCaiNewLeftAdapter(getActivity(), applyListBeanList);

        recyclerviewLeft.setAdapter(jingLiLeftAdapter);
        jingLiLeftAdapter.setOnItemClickListener(this);
//        getMyData(token, "0", startTime, endTime);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;
        startTime = data;
        endTime = data;

        String replace_data = data.replace("-", ".");
        Log.d("replace_data", replace_data);
        textview_calendafirst.setText(replace_data);
        textview_calendasecond.setText(replace_data);

        getMyData(token, "0", "", "", pageNumber, "");
        recyclerview_right.setLayoutManager(new LinearLayoutManager(getActivity()));


        recyclerview_right.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                // 根据原position判断该item是否是parent item
                if (jingLiExpandedAdapter.isParentItem(position)) {
                    // 换取parent position
                    final int parentPosition = jingLiExpandedAdapter.parentItemPosition(position);
                    // 判断parent是否打开了二级菜单
                    if (jingLiExpandedAdapter.isExpanded(parentPosition)) {
                        applyListBeanList.get(parentPosition).setExpanded(false);
                        jingLiExpandedAdapter.notifyParentChanged(parentPosition);
                        // 关闭该parent下的二级菜单
                        jingLiExpandedAdapter.collapseParent(parentPosition);
                    } else {
                        applyListBeanList.get(parentPosition).setExpanded(true);
                        jingLiExpandedAdapter.notifyParentChanged(parentPosition);
                        // 打开该parent下的二级菜单
                        jingLiExpandedAdapter.expandParent(parentPosition);
                    }
                } else {
                    // 换取parent position
                    int parentPosition = jingLiExpandedAdapter.parentItemPosition(position);
                    // 换取child position
                    int childPosition = jingLiExpandedAdapter.childItemPosition(position);
                    String message = String.format("我是%1$d爸爸的%2$d儿子", parentPosition, childPosition);
//                    Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                    jingLiExpandedAdapter.setCheckedPosition(childPosition, parentPosition);
                    Log.d("applyListBeanList", applyListBeanList.size() + "");

                }
            }


        });

        jingLiExpandedAdapter = new JingLiRightAdapter(getActivity());
        recyclerview_right.setLayoutManager(linearLayoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));
        recyclerview_right.setAdapter(jingLiExpandedAdapter);


        return v;
    }

    List<JingliCaiGouDanModel.DataBean.ApplyListBean> groupList = new ArrayList<>();

    public void getMyData(String token, String st, String startTime, String endTime, int pageNumber, String commodityId) {
        HttpResponse.getConsumeBillList(token, st, startTime, endTime, pageNumber, "", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("JIndglidaishenhe", s);
                BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    if (dataBeanList.size() > 0) {
                        dataBeanList.clear();
                        groupList.clear();
                    }
                    JingliCaiGouDanModel jingliCaiGouDanModel = new JingliCaiGouDanModel();
                    jingliCaiGouDanModel = GsonUtil.GsonToBean(s, JingliCaiGouDanModel.class);
//                dataBeanList = jingliCaiGouDanModel.getData();
                    List<JingliCaiGouDanModel.DataBean> dataBeans = new ArrayList<>();
                    dataBeans = jingliCaiGouDanModel.getData();
                    dataBeanList.addAll(dataBeans);
                    if (dataBeans.size() == 0) {
                        layout_nodata.setVisibility(View.VISIBLE);
                        layout_data.setVisibility(View.GONE);
                    } else if (dataBeans.isEmpty()) {
                        layout_nodata.setVisibility(View.GONE);
                        layout_data.setVisibility(View.VISIBLE);
                    }
                    if (dataBeanList.size() > 0) {
                        if (leftArr.size() > 0) {
                            leftArr.clear();
                        }
                        for (int i = 0; i < dataBeans.size(); i++) {
                            leftArr.add(dataBeans.get(i).getLimitData());
                        }
                        if (applyListBeanList.size() > 0) {
                            applyListBeanList.clear();
                        }
//                        applyListBeanList = jingliCaiGouDanModel.getData();
                        applyListBeanList.addAll(jingliCaiGouDanModel.getData());
                        jingLiLeftAdapter.setDataList(applyListBeanList);
//                        groupList = applyListBeanList.get(0).getApplyList();
                        groupList.addAll(applyListBeanList.get(0).getApplyList());
                        jingLiExpandedAdapter.setGroupList(groupList);
                        jingLiExpandedAdapter.notifyDataSetChanged();
                    }
                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                layout_nodata.setVisibility(View.VISIBLE);
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

    }


    @OnClick({R.id.btn_suofang, R.id.img_list, R.id.ll_mycollection_bottom_dialog, R.id.btn_digndan, R.id.layout_calenda_first, R.id.layout_calenda_second})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_calenda_first:
                pvTime.show(layout_calenda_first);
                break;
            case R.id.layout_calenda_second:
                pvTime.show(layout_calenda_second);
                break;
            case R.id.btn_suofang:
                btn_digndan.setVisibility(View.GONE);
                btnSuofang.setVisibility(View.VISIBLE);
                imgList.setVisibility(View.VISIBLE);
                break;
            case R.id.img_list:
                imgList.setVisibility(View.GONE);
                btn_digndan.setVisibility(View.VISIBLE);
                btnSuofang.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_mycollection_bottom_dialog:
                break;
            case R.id.btn_digndan:
//                startActivity(new Intent(getActivity(), JingLiDingDanActivity.class));
                startActivity(new Intent(getActivity(), JingLiNewDingDanActivity.class));
                break;
        }
    }

    public void getCaneda() {

        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2018, 0, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(2033, 12, 31);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_calenda_first:
                        textview_calendafirst.setText(getTime(date));
                        startTime = getTime(date);
                        Integer i = startTime.compareTo(endTime);
                        String replace_data = getTime(date).replace("-", ".");
                        Log.d("replace_data", replace_data);
                        textview_calendafirst.setText(replace_data);
                        if (i > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            getMyData(token, "0", startTime, endTime, 1, "");
                        }
                        break;
                    case R.id.layout_calenda_second:

                        endTime = getTime(date);
//                        getMyData();
                        Integer i1 = startTime.compareTo(endTime);
                        if (i1 > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
//                            textview_calendasecond.setText(getTime(date));
                            String replace_data1 = getTime(date).replace("-", ".");
                            Log.d("replace_data", replace_data1);
                            textview_calendasecond.setText(replace_data1);
                            getMyData(token, "0", startTime, endTime, 1, "");
                        }

                        break;
                }


            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });

                    }

                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))

                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @Override
    public void onItemClick(View view, int adapterPosition) {

    }

    @Override
    public void onItemClickListener(View view, int pos, JingLiCaiNewLeftAdapter.ViewName viewName, List<JingliCaiGouDanModel.DataBean> mMyLiveList) {
        jingLiLeftAdapter.setCheckedPosition(pos);
        Log.d("applyListBeanList", applyListBeanList.size() + "");
        groupList.clear();
        if (pos == 0) {
            groupList.addAll(applyListBeanList.get(0).getApplyList());
            jingLiExpandedAdapter.setGroupList(groupList);
            jingLiExpandedAdapter.notifyDataSetChanged();

        } else {
            groupList.addAll(mMyLiveList.get(pos).getApplyList());
            jingLiExpandedAdapter.setGroupList(groupList);
            jingLiExpandedAdapter.notifyDataSetChanged();
        }
        Log.d("onItemClickListener", MyStringUtils.beanToString(applyListBeanList.get(pos).getApplyList()));


    }
}